<template>
  <div class="maina">
    <arrow :topList="topList"></arrow>
    <div>
      <div class="content">
        <article class="content_box">
          <div class="title_left">内容管理 > 我的作品</div>
          <!-- <div @click="goEdit()">点我详情list，编辑或者添加</div> -->
          <div class="app-container">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
              label-width="100px">
              <el-form-item label="关键词：" style="margin-left: -45px;" prop="keyword">
                <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="作品状态：" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择作品状态">
                  <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8" style="margin-left: -23px;">
              <el-col :span="1.5">
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table stripe v-loading="loading" :data="topicList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="内容编号" width="180" prop="topicXh" />
              <!-- <el-table-column label="展示编号" align="center" prop="topicXh" /> -->
              <el-table-column label="内容名称" align="center" prop="title" />
              <el-table-column label="内容目标" align="center" prop="target" />
              <el-table-column label="内容开始时间" align="center" prop="startTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="内容类型" align="center" prop="type" />
              <el-table-column label="内容状态" align="center" prop="onlineState" />
              <el-table-column label="授权状态" align="center" prop="downloadCopyrightType" />
              <el-table-column label="发布状态" align="center" prop="releaseState" />
              <!-- <el-table-column label="审核意见" align="center" prop="examineFailedReason" /> -->
              <el-table-column label="是否原创" align="center" prop="articleCopyrightType" />
              <el-table-column label="授权对象" align="center" prop="accountName" />
              <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">

                <template slot-scope="scope">
                  <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button> -->
                  <div>
                    <p style="display: flex">
                      <el-button size="small" plain icon="el-icon-search" @click="handleExam(scope.row)">预览</el-button>
                      <el-button size="small" type="danger" plain icon="el-icon-delete"
                        @click="handleDelete(scope.row)">删除</el-button>
                    </p>
                    <p style="display: flex;">
                      <el-button size="small" type="success" plain icon="el-icon-edit-outline"
                        @click="publish(scope.row, 'fabu')"
                        v-if="scope.row.releaseState == '发布失败' || scope.row.releaseState == undefined">发布</el-button>
                      <!-- <el-button size="small" type="info" plain icon="el-icon-edit-outline"
                        @click="publish(scope.row, 'xiajia')" v-if="scope.row.onlineState == '已发布'">下架</el-button> -->
                    </p>

                  </div>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </article>
      </div>

      <el-dialog v-bind="$attrs" v-on="$listeners" width="950px" :visible.sync="submitDia" @open="onOpen"
        @close="onClose" center title="发布">
        <div style="height: 350px;">
          <el-row :span="24">
            <el-form ref="diaForm" :model="formData" :rules="rules" size="medium" label-width="120px">
              <el-col :span="12" style="padding-left: 35px;">
                <el-form-item label-width="120px" label="授权账号：" prop="person">
                  <el-select v-model="formData.person" placeholder="请选择账号">
                    <el-option v-for="item in authMyList" :key="item.value" :label="item.accountName"
                      :value="item.accountId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="平台渠道：">
                  <el-select v-model="formData.platform" disabled placeholder="请选择平台渠道" clearable>
                    <el-option v-for="(item, index) in platformOptions" :key="index" :label="item.label"
                      :value="item.value" :disabled="item.disabled"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="授权协议：" prop="Isauth" style="padding-left: 36px;">
                  <el-button type="primary" icon="el-icon-cloudy" size="medium" @click="popTwo = true"> 授权协议签署
                  </el-button>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div style="display: flex;">
                  <el-form-item label="操作类型：" prop="actionType" style="padding-left: 36px;">
                    <el-radio-group v-model="formData.actionType" size="medium">
                      <el-radio v-for="(item, index) in actionTypeOptions" :key="index" :label="item.value"
                        :disabled="item.disabled">{{ item.label }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-tooltip placement="top" style="cursor: pointer;">
                    <div slot="content">
                      <p> 群发与发布的区别：</p>
                      <p>群发：会主动推送给已关注的全部粉丝，内容消息会显示实时消息界面和公众号主页的历史消息中。服务号每月可群发4次，订阅号每天可群发1次。</p>
                      <p>发布：不会主动推送给粉丝，不会显示在实时消息界面和公众号主页的历史消息中，不限制发布次数。</p>
                    </div>
                    <div style="color: #165DFF;line-height: 36px;padding-left: 40px;">查看群发和发布的区别</div>
                  </el-tooltip>

                </div>
              </el-col>
              <el-col :span="24" style="padding-left: 35px;">
                <el-form-item label="定时发布：" prop="actionHandle">
                  <el-radio-group v-model="formData.actionHandle" size="medium">
                    <el-radio v-for="(item, index) in actionHandleOptions" :key="index" :label="item.value"
                      :disabled="item.disabled">{{ item.label }}</el-radio>

                  </el-radio-group>
                  <span style="padding-left:30px" v-if="formData.actionHandle == 2">
                    <el-date-picker v-model="subTime" type="datetime" placeholder="选择日期时间">
                    </el-date-picker>
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <div style="text-align:center;padding-top: 40px;"><el-button type="primary" size="medium" @click="formSubmit"> 提交发布设置
                  </el-button></div>
              </el-col>
            </el-form>
          </el-row>
        </div>
        <!-- <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div> -->

      </el-dialog>
      <shengming @updateProps="updateProps" @shouquan="shouquan" :isNotice="popTwo"></shengming>
      <shenheView :preOpen="preOpen" :myRow="myRow" :isForm="false" @updatePre="updatePre"></shenheView>
    </div>
  </div>
</template>

<script>
import arrow from '@/views/components/arrow'
import shenheView from '@/views/components/shenheview'
import shengming from '@/views/content/xuanti/shengming'
import { listTopic, delMytopicChuGao } from '@/api/my/xuanti'
import { chugaoList, chengpinList, systemAuthLists, report } from '@/api/my'

export default {
  components: { arrow, shengming, shenheView },
  name: '',
  data() {
    return {
      preOpen: false,
      myRow: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文章选题表格数据
      topicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWords: null,
        articleExamineState: null,
        topicXh: null,
        onlineState: null,
        type: null
        // target: null,
        // digest: null,
        // outline: null,
        // results: null,
        // type: null,
        // schedule: null,
        // userId: null,
        // userName: null,
        // isDelete: null,
        // sourceMaterialId: null,
        // startTime: null,
        // endTime: null
      },
      downloadList: [
        { value: 1, label: '授权下载' },
        { value: 2, label: '开放下载' },
      ],
      processList: [
        { value: 1, label: '素材归集中' },
        { value: 2, label: '内容创作中' },
        { value: 3, label: '创作已完成' },
        { value: 4, label: '已提交审核' },
        { value: 5, label: '已收入成品库' },
        { value: 6, label: '产品分发中' },
      ],
      contentType: [
        { value: 1, label: '图文' },
        { value: 2, label: '视频' },
        { value: 3, label: '音频' },
        { value: 4, label: '动漫' },
        { value: 5, label: '挂图' },
      ],
      status: [
        { value: 0, label: '待发布' },
        { value: 2, label: '发布中' },
        { value: 1, label: '已发布' },
        { value: -1, label: '下架' },
      ],
      openStatus: [
        { value: 0, label: '待发布' },
        { value: 1, label: '发布成功' },
        // { value: 2, label: '发布中' },
        { value: -1, label: '发布失败' },
      ],
      protos: [
        { value: 1, label: '原创' },
        { value: 2, label: '网络' },
        { value: 3, label: '委托' },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // userId: [
        //   { required: true, message: "操作人ID不能为空", trigger: "blur" }
        // ],
        // userName: [
        //   { required: true, message: "操作人姓名不能为空", trigger: "blur" }
        // ],
        // createTime: [
        //   { required: true, message: "创建时间不能为空", trigger: "blur" }
        // ],
      },
      topList: {
        title: '流程指引',
        list: [
          { name: '素材管理', img: 'blue' },
          { name: '内容创作', img: 'blue' },
          { name: '专家审核', img: 'blue' },
          { name: '产品分发', img: 'blue' },
          { name: '传播管理', img: 'gray' },
        ]
      },

      //弹层
      subTime: '',
      submitDia: false,
      formData: {
        person: undefined,    //个人账号授权
        platform: undefined,    //平台渠道，暂未开放
        Isauth: null,  //授权类型 1.授权，2开放
        actionType: 1,    //操作类型  1同步草稿箱 2群发  3发布
        actionHandle: undefined,  //定时发布   1立即发布  2定时发布
        topicId: '',
      },
      rules: {
        Isauth: [{
          required: true,
          message: '请选择授权协议类型',
          trigger: 'blur'
        }],
        person: [{
          required: true,
          message: '请选择账号',
          trigger: 'change'
        }],
        platform: [{
          required: true,
          message: '请选择下拉选择平台渠道',
          trigger: 'change'
        }],
        actionType: [{
          required: true,
          message: '操作类型不能为空',
          trigger: 'change'
        }],
        actionHandle: [{
          required: true,
          message: '定时发布不能为空',
          trigger: 'change'
        }],
      },
      personOptions: [{
        "label": "选项一",
        "value": 1
      }, {
        "label": "选项二",
        "value": 2
      }],
      platformOptions: [{
        "label": "选项一",
        "value": 1
      }, {
        "label": "选项二",
        "value": 2
      }],
      actionTypeOptions: [{
        "label": "同步至草稿箱（需手动发布内容）",
        "value": 1
      }, {
        "label": "一键群发内容",
        "value": 2,
        'disabled': true
      }, {
        "label": "一键发布内容",
        "value": 3
      }],
      actionHandleOptions: [{
        "label": "立即操作",
        "value": 1
      }, {
        "label": "定时发布",
        "value": 2
      }],
      popTwo: false,  //授权弹出，弹窗中的弹窗
      authMyList: [],
    }
  },
  created() {
    this.getList();
    this.AuthList()
  },
  methods: {
    updatePre(val) {
      this.preOpen = val
    },
    async postData() {
      let data = {
        authorizedAccountIdList: [this.formData.person],  //个人账号授权
        copyrightType: Number(this.formData.Isauth),  //授权类型 1.授权，2开放
        onlineState: this.formData.actionHandle.toString(),  //定时发布   1立即发布  2定时发布
        operationType: this.formData.actionType,    //操作类型  1同步草稿箱 2群发  3发布
        topicId: this.formData.topicId
      }
      if (this.subTime) {   //有就传上线时间
        data['onlineTime'] = this.subTime
      }
      if (data.onlineState == '2' && this.subTime.length < 1) {
        this.$notify.error({
          title: '消息',
          message: '请选择发布时间'
        });
        //console.log(data, 'dingshi');
        return
      }
      //console.log(data);
      //  return
      let res = await report(data)
      if (res.code == 200) {
        this.$notify.success({
          title: '消息',
          message: '提交成功'
        })
      }
      this.getList()
      this.submitDia = false
      //console.log(res,'post');
      //  this.submitDia = false  //关闭发布弹层
    },
    formSubmit() {
      if (this.formData.Isauth == null) {
        this.$notify.info({
          title: '消息',
          message: '请选择授权协议类型'
        });
        return
      }
      this.$refs['diaForm'].validate(valid => {
        if (!valid) return
        // console.log('提交');
        this.postData()
      })
      // formData: {
      //   person: undefined,    //个人账号授权
      //   platform: undefined,    //平台渠道，暂未开放
      //   Isauth: null,  //授权类型 1.授权，2开放
      //   actionType: 1,    //操作类型  1同步草稿箱 2群发  3发布
      //   actionHandle: undefined,  //定时发布   1立即发布  2定时发布
      // },
    },
    async AuthList() {  //授权列表
      let res = await systemAuthLists({ userId: this.$store.state.user.userId })
      if (res.code == 200) {
        this.authMyList = res.rows

      }
      //console.log(res,'----');
    },
    shouquan(val) {
      this.formData.Isauth = val
    },
    updateProps(val) {
      this.popTwo = val
    },
    pickTime() {
      console.log('弹出时间');
    },
    onOpen() { },
    onClose() {
      this.$refs['diaForm'].resetFields()
    },
    close() {
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.$refs['diaForm'].validate(valid => {
        if (!valid) return
        this.close()
      })
    },
    publish(row, type) {
      // console.log(123, row);
      // return
      if (type == 'fabu') { //待发布-》发布
        this.submitDia = true  //发布弹层
        this.formData.topicId = row.topicId

      }
      if (type == 'xiajia') { //已发布-》下架

      }

    },
    handleExam(row) {  //预览
      this.myRow = row
      this.preOpen = true
      //console.log(111, row);
    },
    goEdit() {
      this.$router.push({ path: 'xuanti_edit' })
    },
    /** 查询文章选题列表 */
    getList() {
      this.loading = false;
      chengpinList(this.queryParams).then(response => {
        response.rows.map(v => {
          let typeFind = this.contentType.find(values => values.value == v.type)
          if (typeFind !== undefined) {  //内容类型
            v.type = typeFind.label
          }
          let statusFind = this.status.find(r => r.value == v.onlineState)
          console.log(statusFind, 111);
          if (statusFind !== undefined) {  //审核状态
            v.onlineState = statusFind.label
          }
          let protosFind = this.protos.find(params => params.value == v.articleCopyrightType)
          if (protosFind !== undefined) {
            v.articleCopyrightType = protosFind.label
          }
          let downloadRight = this.downloadList.find(t => t.value == v.downloadCopyrightType)
          if (downloadRight !== undefined) {  //授权状态
            v.downloadCopyrightType = downloadRight.label
          }
          let openList = this.openStatus.find(g => g.value == v.releaseState)
          if (openList !== undefined) {  //分发状态
            v.releaseState = openList.label
          }
          v.target = this.$cutString(v.target, 8)
          v.title = this.$cutString(v.title, 8)
          return v
          // console.log(v);

        })
        this.topicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        topicId: null,
        topicXh: null,
        keyword: null,
        target: null,
        digest: null,
        outline: null,
        results: null,
        type: null,
        schedule: null,
        userId: null,
        userName: null,
        isDelete: null,
        createTime: null,
        updateTime: null,
        sourceMaterialId: null,
        startTime: null,
        endTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.topicId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增文章选题";
      this.$router.push({ path: '/content/xuanti_edit', 'query': { 'type': 1 } })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {  //编辑按钮
      // this.reset();
      // const topicId = row.topicId || this.ids
      // getTopic(topicId).then(response => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改文章选题";
      // });
      // console.log(row);
      this.$router.push({ path: '/content/edit_content', query: { 'type': 2, 'articleId': row.articleId, 'topicId': row.topicId } })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.topicId != null) {
            updateTopic(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTopic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleId = row.articleId || row.topicId || this.ids;
      this.$modal.confirm('是否确认删除内容编号为"' + row.topicXh + '"的数据项？').then(function () {
        // return delTopic(topicIds);
        return delMytopicChuGao(articleId)
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/topic/export', {
        ...this.queryParams
      }, `topic_${new Date().getTime()}.xlsx`)
    }
  },
  watch: {
    submitDia(value) {
      if (!value) {  //关闭了弹层
        this.formData = {
          person: undefined,
          platform: undefined,
          Isauth: undefined,  //授权类型
          actionType: 1,
          actionHandle: undefined,
          topicId: '',
        }
      }
      // console.log(value);
    },
    'formData.actionHandle'(value) {
      if (value == 1) {
        this.subTime = ''  //选立即操作，直接清空定时发布
      }
      //console.log(value);
    }
  },
}
</script>

<style lang='scss' scoped>
.maina {
  background-color: #f5f5f5;

  .content {
    margin-top: 10px;
    background-color: white !important;

    .content_box {
      padding-left: 32px;

      .title_left {

        padding-top: 31px;
        font-size: 16px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 700;
        color: #3D3D3D;
        line-height: 21px;
      }
    }
  }
}
</style>